package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 28242
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-06-26 09:18:59
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public Result login(LoginVo loginVo) {

        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginVo.getUserMobile())
        );
        if (tbUser==null){
            return Result.error().setMsg("该账号不存在");
        }
        if (!tbUser.getUserPass().equals(loginVo.getUserPass())){
            return Result.error().setMsg("密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("nickName", tbUser.getNickName())
                .compact();

        String rediskey="token-"+tbUser.getUserId();

        redisTemplate.opsForValue().set(rediskey,token,15, TimeUnit.MINUTES);


        tbUser.setToken(token);
        tbUser.setUserPass(null);


        return Result.ok().setData(tbUser);
    }
}




